package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.PlaceAdapter;
import com.example.xianji.adapter.EnterpriseAdapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.FuWu;
import com.example.xianji.bean.Place;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Find_QiYeActivity extends Activity implements BGARefreshLayoutDelegate, OnClickListener {
    public static String text_qiye_content = "";//企业搜索的关键词
    public String qiye_hangye_name = "行业分类", qiye_hangye_place = "地区";
    public boolean qiye_hangye_flag = false, qiye_hangye_palce_flag = false;
    private ImageView qiye_liebiao_search, find_qiye_image_load;
    private RelativeLayout find_qiye_relative_back;
    private BGARefreshLayout qiye_RefreshLayout;
    private ListView mlistView;
    private EnterpriseAdapter mQiYe_LieBiao_Adapter;
    private ArrayList<Integer> data;
    private ArrayList<FuWu> gongsi_list = new ArrayList<FuWu>();
    private int page = 1;
    private LinearLayout layout1;
    private GridView province_gridview, qiye_province_gridview;
    private PopupWindow show_popupWindow;
    private RelativeLayout relativelayout_qiye_hangye_fenlei, relativelayout_qiye_place;
    private PlaceAdapter mPlaceAdapter;
    private ArrayList<Place> qiye_hangye_list = new ArrayList<Place>();
    private ArrayList<Place> qiye_place_list = new ArrayList<Place>();
    private TextView text_qiye_hangye, text_qiye_hangye_palce, text_company_list_title;
    private int qiye_hangye_id = 0;
    private int qiye_hanye_place_id = 0;
    //    private SharedPreferences sp;
//    private Editor ed;
    private AnimationDrawable find_qiye_animation;
    private View qiye_translation_view;
    private boolean isShowing = false;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                qiye_RefreshLayout.endRefreshing();
                mlistView.setAdapter(mQiYe_LieBiao_Adapter);
                find_qiye_animation.stop();
                find_qiye_image_load.setVisibility(View.GONE);
            }
            if (msg.what == 2) {
                mQiYe_LieBiao_Adapter.notifyDataSetChanged();
                qiye_RefreshLayout.endLoadingMore();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__find__qi_ye);
	/*	XJApplication.getInstance().addActivity(this);
		XJApplication.getInstance3().addActivity3(this);*/
        find_qiye_relative_back = (RelativeLayout) findViewById(R.id.find_qiye_relative_back);
        qiye_RefreshLayout = (BGARefreshLayout) findViewById(R.id.qiye_RefreshLayout);

        qiye_liebiao_search = (ImageView) findViewById(R.id.qiye_liebiao_search);
        relativelayout_qiye_hangye_fenlei = (RelativeLayout) findViewById(R.id.relativelayout_qiye_hangye_fenlei);
        text_qiye_hangye = (TextView) findViewById(R.id.text_qiye_hangye);
        relativelayout_qiye_place = (RelativeLayout) findViewById(R.id.relativelayout_qiye_place);
        mlistView = (ListView) findViewById(R.id.mlistView);
        text_qiye_hangye_palce = (TextView) findViewById(R.id.text_qiye_hangye_palce);
        text_company_list_title = (TextView) findViewById(R.id.text_company_list_title);
        find_qiye_image_load = (ImageView) findViewById(R.id.find_qiye_image_load);
        find_qiye_animation = (AnimationDrawable) find_qiye_image_load.getDrawable();
        find_qiye_animation.start();
        qiye_province_gridview = (GridView) findViewById(R.id.qiye_province_gridview);
        qiye_translation_view = findViewById(R.id.qiye_translation_view);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        if (text_qiye_content.length() > 0) {
            text_company_list_title.setText(text_qiye_content);
        } else {
            text_company_list_title.setText("企业列表");
        }

        text_qiye_hangye_palce.setText(qiye_hangye_place);
        text_qiye_hangye.setText(qiye_hangye_name);
        mQiYe_LieBiao_Adapter = new EnterpriseAdapter(gongsi_list, Main_Find_QiYeActivity.this);
        XJApplication.cachThreadPool.execute(new Runnable() {

            @Override
            public void run() {
                get_qiye_data();
            }
        });
        find_qiye_relative_back.setOnClickListener(this);
        qiye_liebiao_search.setOnClickListener(this);
        relativelayout_qiye_hangye_fenlei.setOnClickListener(this);
        relativelayout_qiye_place.setOnClickListener(this);
        qiye_RefreshLayout.setDelegate(this);
        processLogic(savedInstanceState);
        qiye_translation_view.setOnClickListener(this);
    }

    protected void processLogic(Bundle savedInstanceState) {
        qiye_RefreshLayout.setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(this, true));
    }

    /**
     * 企业列表
     */
    public void get_qiye_data() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("page", 1 + "");
        map.put("cid", qiye_hangye_id);
        map.put("area", qiye_hanye_place_id);
        map.put("k", text_qiye_content);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.qiye_liebiao,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        JSONArray ay = array.getJSONArray(0);
                        JSONArray ay1 = array.getJSONArray(1);
                        JSONArray ay2 = array.getJSONArray(2);
                        gongsi_list.clear();
                        for (int i = 0; i < ay.length(); i++) {
                            JSONObject object = ay.getJSONObject(i);
                            FuWu mFuWu = new FuWu();
                            JSONArray ayy = object.getJSONArray("cats");
                            if (ayy.length() > 0) {
                                JSONObject obj = ayy.getJSONObject(0);
                                mFuWu.setCat_name(obj.getString("parent_name"));
                            }
                            mFuWu.setTitle(object.getString("title"));
                            mFuWu.setId(object.getInt("id"));
                            mFuWu.setProvince_name(object.getString("province_name"));
                            mFuWu.setCity_name(object.getString("city_name"));
                            gongsi_list.add(mFuWu);
                        }

                        qiye_hangye_list.clear();
                        for (int i = 0; i < ay1.length(); i++) {
                            JSONObject obj1 = ay1.getJSONObject(i);
                            Place mPlace = new Place();
                            mPlace.setArea_id(obj1.getString("id"));
                            mPlace.setArea_name(obj1.getString("name"));
                            qiye_hangye_list.add(mPlace);
                        }
                        qiye_place_list.clear();
                        for (int i = 0; i < ay2.length(); i++) {
                            JSONObject obj2 = ay2.getJSONObject(i);
                            Place mPlace = new Place();
                            mPlace.setArea_id(obj2.getString("area_id"));
                            mPlace.setArea_name(obj2.getString("area_name"));
                            qiye_place_list.add(mPlace);
                        }
                    }
                    handler.sendEmptyMessage(1);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                qiye_RefreshLayout.endRefreshing();
                find_qiye_animation.stop();
                find_qiye_image_load.setVisibility(View.GONE);
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_qiye_data_more() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("page", page + "");
        if (qiye_hangye_flag) {
            map.put("cid", qiye_hangye_id);
        }
        if (qiye_hangye_palce_flag) {
            map.put("area", qiye_hanye_place_id);
        }

        map.put("k", text_qiye_content);
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.qiye_liebiao,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");

                        //array.getJSONArray(0)
                        JSONArray ay = array.getJSONArray(0);

                        if (ay.length() > 0) {
                            for (int i = 0; i < ay.length(); i++) {
                                JSONObject object = ay.getJSONObject(i);
                                FuWu mFuWu = new FuWu();
                                JSONArray ay1 = object.getJSONArray("cats");
                                if (ay1.length() > 0) {
                                    JSONObject obj = ay1.getJSONObject(0);
                                    mFuWu.setCat_name(obj.getString("parent_name"));

                                }

                                mFuWu.setTitle(object.getString("title"));
                                mFuWu.setId(object.getInt("id"));

                                mFuWu.setProvince_name(object.getString("province_name"));
                                mFuWu.setCity_name(object.getString("city_name"));
                                gongsi_list.add(mFuWu);
                            }

                        }
                    } else {
                        Toast.makeText(Main_Find_QiYeActivity.this, "加载完毕没有更多数据", Toast.LENGTH_SHORT).show();
                    }
                    handler.sendEmptyMessage(2);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                qiye_RefreshLayout.endLoadingMore();
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void province_Photo_show() {
        layout1 = (LinearLayout) LayoutInflater.from(
                Main_Find_QiYeActivity.this).inflate(
                R.layout.province_popoupwindow_listview, null);
        province_gridview = (GridView) layout1.findViewById(R.id.province_gridview);
        province_gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        show_popupWindow = new PopupWindow(layout1, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setAnimationStyle(R.style.AnimTopMiddle);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout1);
        show_popupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.relativelayout_qiye_hangye_fenlei) {
            mPlaceAdapter = new PlaceAdapter(this, qiye_hangye_list, 2);
            show();
            refresh_load_stop();
            qiye_province_gridview.setAdapter(mPlaceAdapter);
            qiye_province_gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3) {
                    hide();
                    text_qiye_hangye.setText(qiye_hangye_list.get(arg2).getArea_name());
                    qiye_hangye_flag = true;
                    qiye_hangye_name = qiye_hangye_list.get(arg2).getArea_name();
                    qiye_hangye_id = Integer.parseInt(qiye_hangye_list.get(arg2).getArea_id());
                    get_qiye_data();
                }
            });

        } else if (v.getId() == R.id.qiye_liebiao_search) {
            Intent intent = new Intent(Main_Find_QiYeActivity.this, Main_SearchActivity.class);
            intent.putExtra("search", 6);
            startActivity(intent);
        } else if (v.getId() == R.id.find_qiye_relative_back) {
            PreferenceEngine.getInstance().putInt(Constant.SP.NAME, Constant.SP.KEY_FINISH_FROM, 1);
//            ed.putInt("finish_from", 1);
//            ed.commit();
            Main_Find_QiYeActivity.this.finish();
        } else if (v.getId() == R.id.relativelayout_qiye_place) {
            refresh_load_stop();
            mPlaceAdapter = new PlaceAdapter(this, qiye_place_list, 2);
            show();
            qiye_province_gridview.setAdapter(mPlaceAdapter);

            qiye_province_gridview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3) {
                    hide();
                    text_qiye_hangye_palce.setText(qiye_place_list.get(arg2).getArea_name());
                    qiye_hangye_place = qiye_place_list.get(arg2).getArea_name();
                    qiye_hanye_place_id = Integer.parseInt(qiye_place_list.get(arg2).getArea_id());
                    if (show_popupWindow != null) {
                        show_popupWindow.dismiss();
                        show_popupWindow = null;
                    }
                    qiye_hangye_palce_flag = true;
                    get_qiye_data();
                }
            });
        } else if (v.getId() == R.id.qiye_translation_view) {
            hide();
        }
    }

    private void refresh_load_stop() {
        qiye_RefreshLayout.endRefreshing();
        qiye_RefreshLayout.endLoadingMore();
    }

    protected boolean hide() {
        qiye_province_gridview.setVisibility(View.GONE);
        qiye_translation_view.setVisibility(View.GONE);
        isShowing = false;
        return false;
    }

    private boolean show() {
        qiye_province_gridview.setVisibility(View.VISIBLE);
        qiye_translation_view.setVisibility(View.VISIBLE);
        isShowing = true;
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (text_qiye_content.length() > 0) {
            text_company_list_title.setText(text_qiye_content);
        } else {
            text_company_list_title.setText("企业列表");
        }
        if (Main_SearchActivity.qiye_search_id == 1) {
            get_qiye_data();
            Main_SearchActivity.qiye_search_id = 0;
        }
        refresh_load_stop();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                page = 1;
                get_qiye_data();
            }
        }.sendEmptyMessage(0);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                page++;
                get_qiye_data_more();
            }
        }.sendEmptyMessage(0);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (!isShowing) {
            super.onBackPressed();
        } else {
            hide();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        text_qiye_content = "";
        handler.removeCallbacksAndMessages(null);
    }
}
